<template>
  <div class="container">
    <div v-show="!iscrop" style="width: 100%;">
      <div class="title flex">
        <span>客户相册提供高清照片保存({{photos.length}}/10)</span>
      </div>
      <div class="selectphoto flex" @tap="uploadTap">
        <i></i>
      </div>
      <div class="body">
        <div v-for="(item,index) in photos" :key="index">
          <img :src="item.imgurl" @tap="previewImage(index)">
          <div class="delete flex" @tap="deletephoto(item.imgid)">
            <i></i>
            <span>删除</span>
          </div>
        </div>
      </div>
    </div>
    <!-- <div v-show="iscrop">
      <mpvue-cropper ref="cropper" :option="cropperOpt"></mpvue-cropper>
      
      <div class="upload">
        <span @tap="backphoto">返回相册</span>
        <span class="getCropperImage" @tap="getCropperImage">上传图片</span>
      </div>
    </div>-->
    <van-dialog id="van-dialog"/>
  </div>
</template>

<script>
import wx from 'wx'
import api from '@/utils/api'
import Toast from '@/utils/toast'
// import MpvueCropper from 'mpvue-cropper'
import Dialog from '../../../../static/vant/dialog/dialog'
// let wecropper
// const device = wx.getSystemInfoSync()
// const width = device.windowWidth
// const height = device.windowHeight - 50

export default {
  data () {
    return {
      guest_id: '',
      photos: [],
      userInfo: {},
      token: ''
      // cropperOpt: {
      //   id: 'cropper',
      //   width,
      //   height,
      //   scale: 2.5,
      //   zoom: 8,
      //   cut: {
      //     x: (width - 300) / 2,
      //     y: (height - 300) / 2,
      //     width: 300,
      //     height: 300
      //   },
      //   picUrl: '',
      //   isUpdate: false
      // },
      // iscrop: false
    }
  },
  components: {
    // MpvueCropper
  },
  onLoad () {
    const that = this
    //  接收客户id
    that.guest_id = that.$route.query.id
    // 存储员工信息
    that.userInfo = wx.getStorageSync('userInfo')
    that.get_info()
    that.get_token()
  },
  // mounted () {
  //   const that = this
  //   wecropper = that.$refs.cropper
  // },
  methods: {
    // request (query, data, method) {
    //   const now = Date.now()
    //   const appId = 'A6928833419032'
    //   const appKey = sha1(appId + 'UZ' + '4221DC18-42A8-27B0-F17C-0120168E5155' + 'UZ' + now) + '.' + now
    //   return new Promise(function (resolve, reject) {
    //     wx.request({
    //       url: 'https://d.apicloud.com/mcm/api/file' + query,
    //       data: data || '',
    //       header: {
    //         'X-APICloud-AppId': appId,
    //         'X-APICloud-AppKey': appKey
    //       },
    //       method: method || 'GET',
    //       success (res) {
    //         resolve(res)
    //       },
    //       fail (err) {
    //         reject(err)
    //       }
    //     })
    //   })
    // },
    async get_info () {
      const that = this
      const res = await api.getguestalbum({ guestid: that.guest_id })
      that.photos = res
    },
    async get_token () {
      this.token = await api.getqiuniutoken()
    },
    deletephoto (imgid) {
      const that = this
      if (!that.userInfo.authority.guest_del_album) {
        Toast('您没有权限删除相册!', 'noicon')
        return false
      }
      Dialog.confirm({
        title: '提示',
        message: '确定删除本条信息吗?'
      }).then(async () => {
        const res = await api.delqiniuimg({
          key: imgid
        })
        if (res === 'OK') {
          that.delguestalbum(imgid)
        } else {
          Toast('删除失败', 'noicon')
        }
      }).catch(() => {

      })
    },
    async delguestalbum (imgid) {
      const that = this
      const res = await api.postdelguestalbum({
        imgid
      })
      Toast(res.msg, 'noicon')
      if (res.code === '100') {
        that.get_info()
      }
    },
    previewImage (i) {
      const that = this
      wx.previewImage({
        current: that.photos[i].imgurl, // 当前显示图片的http链接
        urls: [that.photos[i].imgurl] // 需要预览的图片http链接列表
      })
    },
    uploadTap () {
      const that = this
      if (!that.userInfo.authority.guest_add_album) {
        Toast('您没有权限添加相册!', 'noicon')
        return false
      }
      // that.iscrop = true
      wx.chooseImage({
        count: 1, // 默认9
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: (res) => {
          const src = res.tempFilePaths[0]
          // that.isUpdate = true
          //  获取裁剪图片资源后，给data添加src属性及其值
          // wecropper.pushOrigin(src)
          const key = Math.random().toString(36).substr(2) // 生成一个随机字符串的文件名
          const houzhui = src.substring(src.length, src.length - 4)
          const keyName = 'customerphotos/' + new Date().getFullYear() + '-' + (new Date().getMonth() + 1) + '-' + new Date().getDate() + '/' + key + houzhui
          wx.uploadFile({
            url: 'https://upload.qiniup.com',
            filePath: src,
            name: 'file',
            formData: {
              'token': that.token.uptoken,
              'key': keyName
            },
            success (res) {
              // that.iscrop = false
              let data = res.data
              data = JSON.parse(data.trim())
              const imgid = data.key
              const imgurl = `http://mytimg.178mr.com/${imgid}`
              that.addguestalbum(imgid, imgurl)
            },
            fail (res) {
              Toast('上传失败!', 'noicon')
            }
          })
        }
      })
    },
    // async getCropperImage () {
    //   let that = this
    //   if (that.isUpdate) {
    //     const token = await api.getqiuniutoken({})
    //     wecropper.getCropperImage()
    //       .then(async (src) => {
    //         const key = Math.random().toString(36).substr(2) // 生成一个随机字符串的文件名
    //         const houzhui = src.substring(src.length, src.length - 4)
    //         const keyName = 'customerphotos/' + new Date().getFullYear() + '-' + (new Date().getMonth() + 1) + '-' + new Date().getDate() + '/' + key + houzhui
    //         wx.uploadFile({
    //           url: 'https://upload.qiniup.com',
    //           filePath: src,
    //           name: 'file',
    //           formData: {
    //             'token': token.uptoken,
    //             'key': keyName
    //           },
    //           success (res) {
    //             that.iscrop = false
    //             let data = res.data
    //             data = JSON.parse(data.trim())
    //             const imgid = data.key
    //             const imgurl = `http://mytimg.178mr.com/${imgid}`
    //             that.addguestalbum(imgid, imgurl)
    //           },
    //           fail (res) {
    //             Toast('上传失败!', 'noicon')
    //           }
    //         })
    //       })
    //       .catch(e => {
    //         console.error('获取图片失败')
    //       })
    //   } else {
    //     Toast('请选择图片', 'noicon')
    //     return false
    //   }
    // },
    async addguestalbum (imgid, imgurl) {
      const that = this
      const res = await api.postaddguestalbum({
        guestid: that.guest_id,
        imgid: imgid,
        imgurl: imgurl
      })
      Toast(res.msg, 'noicon')
      if (res.code === '100') {
        that.get_info()
      }
    }
    // backphoto () {
    //   this.iscrop = false
    // }
  }
}
</script>

<style>
.container {
  height: 100%;
  background-color: rgba(255, 255, 255, 1);
}
.title {
  padding: 22rpx 0;
  font-size: 28rpx;
  color: rgba(102, 102, 102, 1);
}
.selectphoto {
  position: absolute;
  top: 0;
  right: 0;
  width: 100rpx;
  height: 100rpx;
}
.selectphoto i {
  position: relative;
  top: -4rpx;
  width: 50rpx;
  height: 32rpx;
  background: url(http://mytimg.178mr.com/upload.png) no-repeat;
  background-size: 100%;
}
.body {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  width: 100%;
  padding: 0 45rpx;
}
.body > div {
  width: 300rpx;
}
.body > div img {
  width: 100%;
  height: 300rpx;
  vertical-align: middle;
}
.body .delete {
  height: 64rpx;
  font-size: 28rpx;
  color: rgba(102, 102, 102, 1);
}
.body .delete i {
  width: 26rpx;
  height: 30rpx;
  background: url(http://mytimg.178mr.com/delete.png) no-repeat;
  background-size: 100%;
  margin-right: 12rpx;
}
.body .delete span {
  padding-top: 6rpx;
}
.cropper-wrapper {
  position: relative;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  justify-content: center;
  height: 100%;
  background-color: #e5e5e5;
}

.cropper {
  position: absolute;
  top: 0;
  left: 0;
}
.upload {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  justify-content: center;
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 50px;
  line-height: 50px;
  background-color: #fff;
  color: #ff4444;
}
.upload span {
  width: 50%;
  text-align: center;
}
</style>